package com.example.weight.navigation;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.MainActivity;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.model.Station;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FactoryActivity extends AppCompatActivity {
    private Spinner login_station;

    private List<Station> stationList;

    private String factory;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_factory);

        Intent previousIntent = getIntent();
        String name = previousIntent.getStringExtra("name");
        Log.d("name",name);

        String password = previousIntent.getStringExtra("password");
        Log.d("password",password);


        login_station = findViewById(R.id.login_station);
        stationList = (List<Station>) previousIntent.getSerializableExtra("stationList");

        TitleBar titleBar = findViewById(R.id.main_navigation_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {finish();}

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        ArrayAdapter<Station> adapter = new ArrayAdapter<Station>(FactoryActivity.this, android.R.layout.simple_spinner_item ,stationList);
        login_station.setAdapter(adapter);
        login_station.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                factory = stationList.get(position).getFactory();
                Toast.makeText(FactoryActivity.this, "场站已选择：" + stationList.get(position).getName(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                factory = "";
            }
        });
        login_station.setSelection(0,true);



        Button button = findViewById(R.id.factory_button);
        button.setOnClickListener(v -> {
            // 添加登录验证
            RequestQueue queue = Volley.newRequestQueue(this);

            String url = Config.url + "/user/login";
            StringRequest setSysNameRequest = new StringRequest(Request.Method.POST, url,
                    new com.android.volley.Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (!jsonObject.isNull("data")) {
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    Log.d("data", data.toString());
//                                    Log.d("factory", factory);
                                    String permissionLevel = data.getString("permissionLevel");
                                    Intent intent = new Intent(FactoryActivity.this, MainNavigationActivity.class);
                                    intent.putExtra("name", name);
                                    intent.putExtra("permissionLevel", permissionLevel);
                                    intent.putExtra("factory", factory);
                                    Log.d("mainca", factory);
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(FactoryActivity.this,
                                            "用户名或密码错误", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(FactoryActivity.this,
                            "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", name);
                    map.put("password", password);
                    map.put("factory", factory);
                    return map;
                }
            };
            setSysNameRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            queue.add(setSysNameRequest);
        });


    }

//    public void getStationList() {
//        //设置培育料list
//        RequestQueue queue = Volley.newRequestQueue(this);
//        String url = Config.url + "/url/get" + "?pageSize=1000&currentPage=1";
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            if (!jsonObject.isNull("data")) {
//                                JSONArray data = jsonObject.getJSONArray("data");
//                                if( data.length()>0){
//                                    for (int i=0; i < data.length(); i++){
//                                        JSONObject record = data.getJSONObject(i);
//                                        stationList.add(new Station(record.getInt("id"),record.getString("name"),record.getString("identification")));
//                                    }
//                                    Log.d("batchGroupNumberList", stationList.toString());
//
//                                    ArrayAdapter<Station> adapter = new ArrayAdapter<Station>(MainActivity.this, android.R.layout.simple_spinner_item ,stationList);
//                                    login_station.setAdapter(adapter);
//                                    login_station.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                        @Override
//                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                            factory = stationList.get(position).getIdentification();
//                                        }
//                                        @Override
//                                        public void onNothingSelected(AdapterView<?> parent) {
//                                            factory = "";
//                                        }
//                                    });
//                                    login_station.setSelection(0,true);
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(MainActivity.this,
//                        "获取设备名称失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);
//
//    }
}